<template>
  <div class="Mini">
    <el-breadcrumb>
      <el-breadcrumb-item>房型管理</el-breadcrumb-item>
      <el-breadcrumb-item>Mini吧设置</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="easy-content">
      <el-form>
        <el-form-item style="margin-bottom:0;">
          <div class="order-warpper">
            <div class="group-2">
              <el-dropdown @command="setState">
                <span class="el-dropdown-link">
                  {{stateStr}}
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{title:'全部状态',id:''}">全部状态</el-dropdown-item>
                  <el-dropdown-item :command="{title:'上架',id:'1'}">上架</el-dropdown-item>
                  <el-dropdown-item :command="{title:'下架',id:'2'}">下架</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="group-1">
              <input autocomplete="off"
                placeholder="请输入商品名称/拼音/编号"
                type="text"
                rows="2"
                validateevent="true"
                class="el-input__inner"
                v-model="search">
            </div>
            <el-button type="primary"
              @click.native="_getGoodsList"
              class="searc"
              style=" line-height: 32px;padding: 0 21px;">
              <i class="el-icon-search"></i>
            </el-button>
            <el-button type="primary"
              class="searc"
              style=" line-height: 32px;padding: 0 21px;float:right"
              @click.native="add"
              v-has="'miniaddchange'">
              新增商品
            </el-button>
            <el-button type="primary"
              class="searc"
              style=" line-height: 32px;padding: 0 21px;float:right"
              @click.native="_pmsCommon"
              v-has="'miniproduct'">
              商品同步
            </el-button>
            <el-button type="primary"
              class="searc"
              style=" line-height: 32px;padding: 0 21px;float:right"
              @click.native="_edit_mini"
              v-has="'minipayinfo'">
              mini吧开关及支付设置
            </el-button>
          </div>
        </el-form-item>

        <div class="Mini-content">
          <div class="Mini-nav fl">
            <el-tree :data="typeList"
              :props="defaultProps"
              @node-click="handleNodeClick"></el-tree>
            <el-button type="primary"
              class="editType"
              style=" line-height: 32px;padding: 0 21px;"
              @click.native="editType"
              v-has="'minitypelist'">
              维护分类
            </el-button>
          </div>
          <div class="Mini-table fr">
            <el-form-item class="easy-table">
              <el-table :data="getGoodsList"
                style="width: 100%"
                max-height="600">
                <el-table-column prop="name"
                  label="商品名称"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="spellName"
                  label="商品拼音"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="num"
                  label="PMS编号"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="photo"
                  label="图片"
                  min-width="100">
                  <template slot-scope="scope">
                    <img :src="scope.row.photo"
                      alt=""
                      width="30%"
                      style="display:block">
                  </template>
                </el-table-column>
                <el-table-column prop="type"
                  label="商品分类"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="salePrice"
                  label="商品价格"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="unit"
                  label="单位"
                  min-width="100">
                </el-table-column>
                <el-table-column prop="state"
                  label="状态"
                  min-width="100">
                  <template slot-scope="scope">
                    <span>{{scope.row.state == 1? '正常':'失效'}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="updateTime"
                  label="最新同步时间"
                  min-width="100">
                </el-table-column>
                <el-table-column fixed="right"
                  label="操作"
                  width="200">
                  <template slot-scope="scope">
                    <el-button type="text"
                      size="small"
                      @click="editGoods(scope.row.id)"
                      v-has="'miniaddchange'">编辑</el-button>
                    <el-button type="text"
                      size="small"
                      :disabled="scope.row.state  == 1"
                      @click.native="editGoodsState(scope.row)"
                      v-has="'ministate'">上架</el-button>
                    <el-button type="text"
                      size="small"
                      :disabled="scope.row.state == 2"
                      @click.native="editGoodsState(scope.row)"
                      v-has="'ministate'">下架</el-button>
                    <el-button type="text"
                      size="small"
                      @click="_deleteGoods(scope.row.id)"
                      v-has="'minidelete'">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item>
              <el-pagination @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNo"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, prev , pager , next, sizes"
                :total="total"
                style="margin-top:20px">
              </el-pagination>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <!-- 新增商品 -->
      <el-dialog width="600px"
        :title="title"
        :visible.sync="update_popule"
        @close="_rest('updateData')">
        <el-form :rules="rules"
          ref="updateData"
          :model="updateData"
          label-width="80px"
          class="addUpdate-pouple">
          <el-form-item label="PMS编号"
            prop="num">
            <el-input type="text"
              v-model="updateData.num"
              placeholder="请输入PMS编号"
              maxlength="5"
              @keyup.native="updateData.num = formatInput(updateData.num)"></el-input>
          </el-form-item>
          <div class="inline-block">
            <el-form-item label="商品名称"
              prop="name">
              <el-input type="text"
                v-model="updateData.name"
                placeholder="请输入商品名称"
                maxlength="5"
                @keyup.native="updateData.name = formatInput(updateData.name)"></el-input>
            </el-form-item>
            <el-form-item label="商品拼音"
              prop="spellName">
              <el-input type="text"
                v-model="updateData.spellName"
                placeholder="请输入商品拼音"
                maxlength="5"
                @keyup.native="updateData.spellName = formatInput(updateData.spellName)"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="商品图片">
            <el-upload class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :http-request="sendChange">
              <img v-if="updateData.photo"
                :src="updateData.photo"
                class="avatar"
                width="88"
                height="88" />
              <i v-else
                class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品分类"
            prop="typeId">
            <el-cascader :options="typeList"
              change-on-select
              :props="props"
              v-model="updateData.typeId"></el-cascader>
          </el-form-item>
          <div class="inline-block">
            <el-form-item label="商城价格"
              prop="salePrice">
              <el-input type="text"
                v-model="updateData.salePrice"
                placeholder="请输入商城价格"
                maxlength="5"
                @keyup.native="updateData.salePrice = formatInput(updateData.salePrice)">></el-input>
            </el-form-item>
            <el-form-item label="进货价格"
              prop="basePrice">
              <el-input type="text"
                v-model="updateData.basePrice"
                placeholder="请输入进货价格"
                maxlength="5"></el-input>
            </el-form-item>
          </div>
          <div class="inline-block">
            <el-form-item label="单位"
              prop="unit">
              <el-input type="text"
                v-model="updateData.unit"
                placeholder="请输入物品单位"
                maxlength="3"
                @keyup.native="updateData.unit = formatInput(updateData.unit)"></el-input>
            </el-form-item>
            <el-form-item label="库存"
              prop="inventory">
              <el-input type="text"
                v-model="updateData.inventory"
                placeholder="请输入库存"
                maxlength="5"></el-input>
            </el-form-item>
          </div>
          <div class="inline-block">
            <el-form-item label="预警上限"
              prop="upperLimit">
              <el-input type="text"
                v-model="updateData.upperLimit"
                placeholder="请输入预警上限"
                maxlength="5"></el-input>
            </el-form-item>
            <el-form-item label="预警下限"
              prop="lowerLimit">
              <el-input type="text"
                v-model="updateData.lowerLimit"
                placeholder="请输入预警下限"
                maxlength="5"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="距离上架时间相隔">
            <el-select v-model="updateData.putawayDate"
              placeholder="请选择">
              <el-option v-for="item in times"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input type="textarea"
              v-model="updateData.describes"
              placeholder="请输入商品描述"
              maxlength="50"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer"
          class="dialog-footer">
          <el-button type="primary"
            @click="_addEditGoods('updateData')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- mini吧开关及支付设置 -->
      <el-dialog width="600px"
        :title="title"
        :visible.sync="update_mini">
        <el-form :model="ruleForm_mini"
          :rules="rules_mini"
          ref="ruleForm_mini"
          label-width="150px"
          class="demo-ruleForm">
          <el-form-item label="会员端MINI吧开关"
            required>
            <el-radio-group v-model="ruleForm_mini.onOff">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="2">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="会员端MINI吧支付方式"
            style="position:relative;"
            required
            v-if="ruleForm_mini.onOff ==1">
            <el-radio v-model="ruleForm_mini.type"
              :label="1"
              v-if="modeType!=2">押金抵扣</el-radio>
            <el-radio v-model="ruleForm_mini.type"
              :label="2">微信支付</el-radio>
            <el-radio v-model="ruleForm_mini.type"
              :label="3"
              v-if="modeType!=2">全选</el-radio>

          </el-form-item>
          <el-form-item prop="input_val"
            v-if="ruleForm_mini.type!=2 && ruleForm_mini.onOff ==1">
            <div>
              可用
              <el-input-number v-model="ruleForm_mini.input_val"
                :disabled="disabled_mini"
                controls-position="right"
                :min="1"
                :max="100"
                style="width:100px"
                size="small"></el-input-number> %的押金抵扣消费<br/>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer"
          class="dialog-footer">
          <el-button type="primary"
            @click="submitForm('ruleForm_mini')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
const Breadcrumb = () => import("@/components/common/Breadcrumb");
import { upimg } from "@/public/js/setting.js";
import { formatInput } from "@/public/js/util";

import {
  getTypeList,
  getGoodsList,
  updateGoodsState,
  addEditGoods,
  pmsCommon,
  deleteGoods,
  getGood,
  getMiNiInfo,
  getMiNiRedact
} from "@/public/js/goods.js";
import { setMessageState } from "../../../public/js/message";
export default {
  components: {
    Breadcrumb
  },
  data() {
    var validateEveryPrice = (rule, value, callback) => {
      let re = /[^\d.]/g;
      if (value == "" || value == null) {
        callback(new Error("请输入商城价格"));
      } else if (re.test(value)) {
        callback(new Error("请您输入正确的格式"));
      } else {
        callback();
      }
    };
    //
    var validateEverySpell = (rule, value, callback) => {
      let re = /^[A-Za-z]+$/;
      if (value == "" || value == null) {
        callback(new Error("请输入商品拼音"));
      } else if (!re.test(value)) {
        callback(new Error("请您输入正确的格式"));
      } else {
        callback();
      }
    };
    // 进货价格
    var validateBasePrice = (rule, value, callback) => {
      let re = /[^\d.]/g;
      console.log(value);
      if (re.test(value) && value) {
        callback(new Error("请您输入正确的格式"));
      } else {
        callback();
      }
    };
    // 正整数
    var validatePositiveInteger = (rule, value, callback) => {
      let re = /^[0-9]\d*$/;
      console.log(value);
      if (!re.test(value) && value) {
        callback(new Error("请您输入正整数"));
      } else {
        callback();
      }
    };
    return {
      content: {
        firstTitle: "设置",
        secondTitle: "Mini吧管理",
        type: "close"
      },
      modeType: "",
      roomStatusHueList: [],
      Pouple_name: false,
      staffStatusName: "",
      colorData: {},
      rules: {
        num: [{ required: true, message: "请输入PMS编号", trigger: "blur" }],
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        spellName: [
          { validator: validateEverySpell, trigger: "blur", required: true }
        ],
        typeId: [
          {
            type: "array",
            required: true,
            message: "请选择商品分类",
            trigger: "blur"
          }
        ],
        salePrice: [
          { validator: validateEveryPrice, trigger: "blur", required: true }
        ],
        basePrice: [{ validator: validateBasePrice, trigger: "blur" }],
        unit: [{ required: true, message: "请输入物品单位", trigger: "blur" }],
        inventory: [{ validator: validatePositiveInteger, trigger: "blur" }],
        upperLimit: [{ validator: validatePositiveInteger, trigger: "blur" }],
        lowerLimit: [{ validator: validatePositiveInteger, trigger: "blur" }]
      },
      rules_mini: {
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个会员端MINI吧支付方式",
            trigger: "change"
          }
        ],
        onOff: [
          {
            required: true,
            message: "请选择会员端MINI吧开关",
            trigger: "change"
          }
        ],
        input_val: [
          {
            required: true,
            message: "请输入押金抵扣消费金额",
            trigger: "blur"
          }
        ]
      },
      formatInput,
      pageNo: 1,
      pageSize: 10,
      search: "",
      status: "",
      total: 0,
      breakGoodsList: [],
      stateStr: "商品状态",
      title: "新增物品",
      updateData: {},
      update_popule: false,
      update_mini: false, //mini吧
      handleType: 0,
      getGoodsList: [],
      /***** */
      typeList: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      props: {
        value: "id",
        children: "children",
        label: "label"
      },
      typeId: "",
      state: "",
      times: [
        {
          value: "15天",
          label: "15天"
        },
        {
          value: "30天",
          label: "30天"
        },
        {
          value: "45天",
          label: "45天"
        },
        {
          value: "60天",
          label: "60天"
        },
        {
          value: "75天",
          label: "75天"
        },
        {
          value: "90天",
          label: "90天"
        }
      ],
      ruleForm_mini: {
        type: [],
        onOff: 2,
        input_val: ""
      },
      miNiPayInfo_mini: "",
      disabled_mini: false,
      IsType: true
    };
  },
  created() {
    this._getTypeList();
    this._getGoodsList();
  },

  mounted() {},
  methods: {
    // 获取类型列表 （左侧导航条）
    _getTypeList() {
      getTypeList().then(res => {
        this.typeList = res.data.data;
        //console.log(res.data);
      });
    },
    // 获取MiNi商品列表
    _getGoodsList() {
      getGoodsList({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        search: this.search,
        state: this.state,
        typeId: this.typeId
      }).then(res => {
        this.getGoodsList = res.data.commList;
        this.total = res.data.total;
      });
    },
    _getMiNiInfo() {
      getMiNiInfo().then(res => {
        this.modeType = res.data.modeType;
        this.miNiPayInfo_mini = res.data.miNiPayInfo;
        this.ruleForm_mini.onOff = res.data.miNiPayInfo.onOff
          ? res.data.miNiPayInfo.onOff
          : 2;
        this.ruleForm_mini.input_val = res.data.miNiPayInfo.percent
          ? res.data.miNiPayInfo.percent
          : undefined;
        this.ruleForm_mini.type = res.data.miNiPayInfo.pay
          ? res.data.miNiPayInfo.pay
          : 2;
      });
    },
    reset() {
      this.pageSize = 10;
      this.pageNo = 1;
      this._getGoodsList();
    },
    // 分类点击
    handleNodeClick(val) {
      this.typeId = val.id;
      this.reset();
    },
    // 状态筛选
    setState(val) {
      this.state = val.id;
      this.stateStr = val.title;
      this.reset();
    },
    // 维护分类
    editType() {
      this.$router.push({ path: "/index/edit_type" });
    },
    // 同步PMS
    _pmsCommon() {
      pmsCommon().then(res => {
        if (!res.data.errCode) {
          this.$message({
            type: "success",
            message: "同步成功"
          });
          this._getTypeList();
        } else {
          this.$message({
            type: "error",
            message: "同步失败"
          });
        }
      });
    },
    //编辑
    editGoods(id) {
      getGood({ miniId: id }).then(res => {
        if (!res.data.errCode) {
          let data = res.data.miniComm;
          this.updateData = {
            id: data.id,
            num: data.num,
            name: data.name,
            spellName: data.spellName,
            photo: data.photo,
            inventory: data.inventory,
            describes: data.describes,
            typeId: data.type,
            putawayDate: data.putawayDate,
            salePrice: data.salePrice,
            basePrice: data.basePrice,
            unit: data.unit,
            upperLimit: data.upperLimit,
            lowerLimit: data.lowerLimit,
            remark: data.remark
          };
        }
      });
      this.title = "编辑物品";
      this.update_popule = true;
    },
    // 分页
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getGoodsList();
    },
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this._getGoodsList();
    },
    _rest(formName) {
      this.$refs[formName].resetFields();
      this.updateData = {
        num: "",
        name: "",
        spellName: "",
        photo: "",
        inventory: "",
        describes: "",
        type: "",
        typeId: [],
        putawayDate: "",
        salePrice: "",
        basePrice: "",
        unit: "",
        upperLimit: "",
        lowerLimit: "",
        remark: ""
      };
      this.update_popule = false;
    },
    // 增加
    add() {
      setTimeout(() => {
        this.update_popule = true;
        this.title = "增加商品";
      }, 0);
    },
    _edit_mini() {
      //this.ruleForm_mini.onOff = this.ruleForm_mini.onOff;
      this._getMiNiInfo();
      this.update_mini = true;
      this.title = "mini吧开关及支付设置";
    },

    cancel() {
      this.update_mini = false;
    },
    // 编辑状态
    editGoodsState(row) {
      let state = row.state == 1 ? 2 : 1;
      let statusInfo = row.state == 1 ? "下架" : "上架";
      this.$confirm(`是否${statusInfo}该物品`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateGoodsState({
            miniId: row.id,
            state: state
          }).then(res => {
            if (!res.data.errCode) {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            }
            this._getGoodsList();
          });
        })
        .catch(() => {});
    },
    //删除
    _deleteGoods(id) {
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteGoods({
            id: id
          }).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this._getGoodsList();
          });
        })
        .catch(() => {});
    },
    // 新增修改
    _addEditGoods(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.updateData));
          data.type = data.typeId[data.typeId.length - 1];
          delete data.typeId;
          addEditGoods(data).then(res => {
            if (!res.data.errCode) {
              this.$message({
                type: "success",
                message: this.updateData.id ? "新增成功" : "修改成功"
              });
              this.$refs[formName].resetFields();
              this.update_popule = false;
              this._getGoodsList();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 新增mini
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var data = {
            id: this.miNiPayInfo_mini.id,
            onOff: this.ruleForm_mini.onOff,
            pay: this.ruleForm_mini.type,
            percent:
              this.ruleForm_mini.type == 2
                ? undefined
                : this.ruleForm_mini.input_val
          };
          getMiNiRedact(data).then(res => {
            this.update_mini = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    _EditMiNi(value) {
      console.log(value);
    },
    // 上传图片
    sendChange(e) {
      var reader = new FileReader();
      reader.readAsDataURL(e.file);
      reader.onload = e => {
        let photoPath = e.target.result;
        upimg({
          nowPath: photoPath,
          oldPath: this.updateData.photo
        }).then(res => {
          this.updateData.photo = res.data.path;
        });
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.order-warpper {
  .group-1 {
    width: 300px;
    display: inline-block;
    margin-right: 20px;
  }
  .group-2 {
    width: 80px;
    display: inline-block;
    margin-right: 20px;
  }
  .group-3 {
    margin-top: 20px;
  }
  .btn {
    text-align: right;
  }
  .el-input__inner {
    height: 34px;
  }
  .search-button .el-button {
    padding: 9px 20px;
  }
}
.Mini {
  text-align: left;
  .el-date-editor--daterange.el-input__inner {
    padding: 0;
    padding-left: 10px;
    width: auto;
  }

  .el-input,
  .el-cascader {
    width: 100%;
  }

  .easy-search-other {
    width: 300px;
  }
  .Mini-content {
    display: flex;
    .Mini-nav {
      width: 200px;
      margin-top: 20px;
      min-height: 500px;
      background: #eef1f9;
      margin-right: 20px;
      position: relative;
      .el-tree {
        padding-top: 13px;
      }
      .editType {
        position: absolute;
        bottom: 20px;
        left: 50%;
        margin-left: -50px;
      }
      & * {
        background: #eef1f9;
      }
    }
    .Mini-table {
      flex: 1;
    }
    .addUpdate-pouple {
      .el-input__inner {
        width: 100%;
      }
    }
  }
}
.account-content {
  & > div {
    display: flex;
    padding-bottom: 15px;
    & > div {
      flex: 1;
    }
  }
}
.miNiCommListTable {
  border: 1px solid #ddd;
  border-right: 0;
  li {
    display: flex;
    border-bottom: 1px solid #ddd;

    div {
      flex: 1;
      line-height: 45px;
      font-size: 12px;
      text-indent: 23px;
      border-right: 1px solid #ddd;
    }
    &.header > div {
      background: #eef1f9;
      color: #415161;
    }
    & > .input-number .input-number-count {
      text-align: center;
      text-indent: 0;

      p {
        display: inline-block;
        background: #6d2377;
        height: 30px;
        line-height: 30px;
        width: 30px;
        border-radius: 5px 0 0 5px;
        color: #fff;
        cursor: pointer;
      }
      input {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        border: none;
        width: 30px;
        text-align: center;
        border: 1px solid #6d2377;
        box-sizing: border-box;
      }
    }
  }
}
.handleBtn {
  float: left;
  height: 47px;
  line-height: 47px;
  padding-left: 15px;
  color: #409eff;
}
.inline-block {
  display: flex;
  & > div.el-form-item {
    flex: 1;
  }
}
</style>


